import { resolve, relative, join } from 'path';
import { existsSync, writeFileSync } from 'fs';
import { defineConfig, Plugin } from 'vite';
import styleImport from 'vite-plugin-style-import';
import vue from '@vitejs/plugin-vue';

/**
 * 模块化处理插件
 */
const swiftPlugin = (args: { root?: string, router?: string }) => {
  args = args || {};
  let root = resolve('src', args.root || 'packages');
  let packages = [];
  try {
    packages = require(join(root, 'enable.json'));
  } catch {
    console.log('请在 ' + root + ' 目录中建立 enable.json');
    process.exit(1);
  }
  let relativePath = relative(resolve('src'), root);
  let routes = [];
  for (let p of packages) {
    if (!existsSync(join(root, p, 'router.ts'))) {
      continue;
    }
    routes.push(`export * as ${p}Routes from './${join(relativePath, p, 'router').replace(/\\/g, '/')}';`);
  }
  if (routes.length > 0) {
    let routerOut = resolve(join('src', args.router || '__routes__.ts'));
    writeFileSync(routerOut, `${routes.join('\n')}\n`);
  }
  return {
    name: 'swift',
    enforce: 'pre'
  } as Plugin;
};

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    swiftPlugin({
      root: 'packages'
    }),
    styleImport({
      libs: [
        {
          libraryName: 'element-plus',
          resolveStyle: (name) => {
            return `element-plus/lib/theme-chalk/${name}.css`;
          },
          resolveComponent: (name) => {
            return `element-plus/lib/${name}`;
          }
        }
      ]
    })
  ],
  resolve: {
    alias: [
      {
        find: '@',
        replacement: resolve(__dirname, 'src')
      },
      {
        find: 'decorates',
        replacement: resolve(__dirname, 'src/assets/decorates')
      }
    ],
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']
  },
  server: {
    host: '0.0.0.0',
    port: 8087
  },
  build: {
    target: 'esnext',
    outDir: 'dist',
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        signin: resolve(__dirname, 'signin/index.html')
      }
    }
  }
});
